package com.girant.picture.aop;

import com.girant.picture.annotation.AuthCheck;
import com.girant.picture.domain.entity.User;
import com.girant.picture.enums.UserRoleEnum;
import com.girant.picture.exception.BusinessException;
import com.girant.picture.exception.ErrorCode;
import com.girant.picture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;


    /**
     * 用户权限校验
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        RequestAttributes requestAttribute =  RequestContextHolder.currentRequestAttributes();//获得请求内的attribute
        HttpServletRequest request = ((ServletRequestAttributes) requestAttribute).getRequest();//arrtibute->包装成request请求
        //获取当前登录用户
        String mustRole = authCheck.mustRole();
        User loginUser = userService.getLoginUser(request);
        //此代码作为没有设置用户级别，mustRole为空时，可以直接执行
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByvalue(mustRole);
        if(mustRoleEnum ==null){
            return joinPoint.proceed();
        }
        //以下代码必须有管理员权限才能通过，但用户没有管理员权限，拒绝
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByvalue(loginUser.getUserRole());
        if(userRoleEnum == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //校验的权限是管理员权限 ，用户权限不等于管理员权限
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //通过校验,进行运行代码
        return joinPoint.proceed();
    }
}
